import { login, logout, getInfo, ddUserLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import Cookies from 'js-cookie'
import qs from 'qs'
const state = {
  token: getToken(),
  name: '',
  isCanalAudit: '',
  code: '',
  avatar: '',
  introduction: '',
  roles: [],
  party: '',
  warehouse_name: '',
  secondUploadDetail: -1,
  driver: {},
  resourcelist: {},
  translatelist: {},
  branch: {},
  client_id: '1e069e240a163e9d2a18f4111ewechat',
  client_secret: 'e7957728041b11ea97dffa163e9d2a30',
  dataType: '',
  warehouse_list: [],
  authorizeDataCode: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_CLIENT_ID: (state, client_id) => {
    state.client_id = client_id
  },
  SET_CLIENT_SECRET: (state, client_secret) => {
    state.client_secret = client_secret
  },

  SET_SECONDUPLOADDETAIL: (state, secondUploadDetail) => {
    state.secondUploadDetail = secondUploadDetail
  },
  SET_BRANCH: (state, branch) => {
    state.branch = branch
  },
  /*   SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
      }, */
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_CODE: (state, code) => {
    state.code = code
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ISCANALAUDIT: (state, isCanalAudit) => {
    state.isCanalAudit = isCanalAudit
  },
  SET_WAREHOUSE_NAME: (state, warehouse_name) => {
    state.warehouse_name = warehouse_name
  },
  SET_AUTHORIZEDATACODE: (state, code) => {
    state.authorizeDataCode = code
  },
  SET_PARTY: (state, party) => {
    state.party = party
  },
  SET_DRIVER: (state, driver) => {
    state.driver = driver
  },
  SET_RESOURCELIST: (state, resourcelist) => {
    state.resourcelist = resourcelist
  },
  SET_TRANSLATELIST: (state, translatelist) => {
    state.translatelist = translatelist
  },
  SET_WAREHOUSE_LIST: (state, warehouseList) => {
    state.warehouse_list = warehouseList
  },
  SET_DATATYPE: (state, dataType) => {
    state.dataType = dataType
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const {
      client_id,
      client_secret,
      grant_type,
      response_type,
      device_id,
      username,
      authorizeDataCode,
      password,
      time
    } = userInfo
    return new Promise((resolve, reject) => {
      login(qs.stringify({
        username: username.trim(),
        client_id: client_id,
        client_secret: client_secret,
        grant_type: grant_type,
        authorizeDataCode: authorizeDataCode,
        response_type: response_type,
        device_id: device_id,
        password: password,
        time: time
      })).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.access_token)
        commit('SET_DATATYPE', data.authorizeData.dataType)
        const datapart = JSON.stringify(data.branch.partyGroupConfigCacheMap)
        commit('SET_BRANCH', data.branch)
        if (datapart === '{}') {
          commit('SET_SECONDUPLOADDETAIL', '')
        } else {
          commit('SET_SECONDUPLOADDETAIL', data.branch.partyGroupConfigCacheMap.orderDetailOperate_secondUploadDetail.configValue)
        }
        setToken(data.access_token)
        Cookies.set('branchCode', data.branch.code)
        Cookies.set('branchName', data.branch.groupName)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 钉钉免密登录
  ddUserLogin({ commit }, parms) {
    return new Promise((resolve, reject) => {
      ddUserLogin(parms).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.access_token)
        commit('SET_DATATYPE', data.authorizeData.dataType)
        const datapart = JSON.stringify(data.branch.partyGroupConfigCacheMap)
        commit('SET_BRANCH', data.branch)
        if (datapart === '{}') {
          commit('SET_SECONDUPLOADDETAIL', '')
        } else {
          commit('SET_SECONDUPLOADDETAIL', data.branch.partyGroupConfigCacheMap.orderDetailOperate_secondUploadDetail.configValue)
        }
        setToken(data.access_token)
        Cookies.set('branchCode', data.branch.code)
        Cookies.set('branchName', data.branch.groupName)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {
          data
        } = response
        if (!data) {
          reject('验证失败，请重新登录')
        }
        var code = data.party.code
        var party = data.party
        var resourcelist = data.resourceList
        // 递归获取 英文/中文参照表
        const translatelist = {}
        function getMenuBtnList(resourcelist, translatelist) {
          for (const item of resourcelist) {
            if (item.children && item.children.length > 0) {
              getMenuBtnList(item.children, translatelist)
            } else {
              const title = item.meta && item.meta.title ? item.meta.title : ''
              const name = item.name
              const obj = JSON.parse('{"' + title + '":"' + name + '"}')
              Object.assign(translatelist, obj)
            }
          }
        }
        getMenuBtnList(resourcelist, translatelist)
        commit('SET_BRANCH', data.branch)
        commit('SET_CODE', code)
        commit('SET_PARTY', party)
        commit('SET_AVATAR', party.headImg)
        commit('SET_RESOURCELIST', resourcelist)
        commit('SET_TRANSLATELIST', translatelist)
        commit('SET_WAREHOUSE_LIST', data.warehouseList)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_RESOURCELIST', {})
        removeToken()
        Cookies.remove('branchCode')
        resetRouter()
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // 动态修改权限
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // 基于角色生成可访问路由图
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
      // 动态添加可访问路由
      router.addRoutes(accessRoutes)

      // 重置访问的视图和缓存的视图
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
